package cn.ctodb.service;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.ctodb.domain.Category;
import cn.ctodb.repository.CategoryRepository;
import cn.ctodb.web.rest.dto.AbnTreeDto;
import cn.ctodb.web.rest.dto.CategoryDto;

@Service
@Transactional
public class CategoryService {

    @Resource
    private CategoryRepository categoryRepository;

    public Category getRoot() {
        return categoryRepository.getOne(1L);
    }

    @Transactional(readOnly = true)
    public List<AbnTreeDto> getTreeDto() {
        List<AbnTreeDto> abnTreeDtos = new ArrayList<>();
        Category root = categoryRepository.findByCode("root");
        abnTreeDtos.add(getDto(root));
        return abnTreeDtos;
    }

    public AbnTreeDto getDto(Category category) {
        AbnTreeDto abnTreeDto = new AbnTreeDto();
        abnTreeDto.setId(category.getId());
        abnTreeDto.setLabel(category.getName());
        Set<Category> set = category.getChildren();
        if (set.size() > 0) {
            Set<AbnTreeDto> c = new LinkedHashSet<>();
            for (Category category2 : set) {
                c.add(getDto(category2));
            }
            abnTreeDto.setChildren(c);
        }
        return abnTreeDto;
    }

    public List<Category> getSelects() {
        List<Category> l = categoryRepository.findAll();
        List<Category> list = new ArrayList<>();
        for (Category category : l) {
            add(list, category);
        }
        return list;
    }

    private void add(List<Category> list, Category category) {
        list.add(category);
        if (category.getChildren() != null) {
            for (Category c : category.getChildren()) {
                add(list, c);
            }
        }
    }

    public Category get(Long id) {
        return categoryRepository.getOne(id);
    }

    public Category getByCode(String code) {
        return categoryRepository.findByCode(code);
    }

    public void up(CategoryDto category) {
        Category c = get(category.getId());
        c.setName(category.getName());
        c.setPid(category.getPid());
        c.setSort(category.getSort());
        c.setCode(category.getCode());
        c.setAtp(category.getAtp());
        c.setCgtp(category.getCgtp());
        c.setMemo(category.getMemo());
    }

    public void add(Category category) {
        categoryRepository.save(category);
    }

    public void del(Long id) {
        categoryRepository.delete(id);
    }

}
